<template>
  <div>
    <el-dialog
      v-toggle-full
      v-loading.lock="loading"
      class="base-dialog order-inspect"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      title="入库验收"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
      @closed="closeDialog"
    >
      <!-- 入库单信息 -->
      <el-divider class="el-divider-specail" content-position="left"
        >入库单信息</el-divider
      >
      <el-form
        ref="formData"
        :model="formData"
        :rules="formDataRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="来源单号">
              {{ formData.orderNum }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务类型">
              {{ formData.orderTypeName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检查类型">
              {{ formData.formTypeName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库仓库">
              {{ formData.storageName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="检验员"
              prop="inspectorId"
              :error="errorMsg.inspectorId"
            >
              <el-select
                ref="selectUser"
                v-model="formData.inspectorId"
                :multiple="false"
                filterable
                placeholder="请选择检验员"
                value-key="id"
              >
                <el-option
                  v-for="item in sysUserOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="检验日期"
              prop="inspectionDate"
              :error="errorMsg.inspectionDate"
            >
              <el-date-picker
                v-model="formData.inspectionDate"
                type="date"
                placeholder="选择检验日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 待检物料 -->
      <el-divider
        class="el-divider-specail el-divider-top"
        content-position="left"
        >待检物料</el-divider
      >
      <el-table
        v-if="formData.products.length > 0"
        :data="formData.products"
        :header-cell-style="{ height: '50px' }"
        :cell-style="{ height: '44px', overflow: 'auto' }"
        style="width: 100%; height: auto; overflow: auto"
      >
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="编号">
          <template slot-scope="scope">
            {{ scope.row.number }}
          </template>
        </el-table-column>
        <el-table-column label="名称">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="别名">
          <template slot-scope="scope">
            {{ scope.row.aliasName }}
          </template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template slot-scope="scope">
            {{ scope.row.size }}
          </template>
        </el-table-column>
        <el-table-column label="分类">
          <template slot-scope="scope">
            {{ scope.row.typeName }}
          </template>
        </el-table-column>
        <el-table-column label="包装单位">
          <template slot-scope="scope">
            {{ scope.row.packingUnit }}
          </template>
        </el-table-column>
        <el-table-column label="应检总数">
          <template slot-scope="scope">
            {{ scope.row.productCount }}
          </template>
        </el-table-column>
        <el-table-column label="已检总数">
          <template slot-scope="scope">
            {{ scope.row.actualCount }}
          </template>
        </el-table-column>
        <el-table-column label="待检总数">
          <template slot-scope="scope">
            {{
              parseInt(scope.row.pendingCount) > 0
                ? scope.row.pendingCount
                : '已完成'
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div v-if="scope.row.pendingCount > 0" class="base-table-operation">
              <el-link
                size="mini"
                type="primary"
                @click="openInspectResultDialog(scope.row)"
                >录入检验结果</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 检验清单 -->
      <el-divider
        class="el-divider-specail el-divider-top"
        content-position="left"
        >检验清单</el-divider
      >
      <el-table
        :data="inspectionChecklist"
        :header-cell-style="{ height: '50px' }"
        :cell-style="{ height: '44px', overflow: 'auto' }"
        style="width: 100%; height: auto; overflow: auto"
      >
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="编号">
          <template slot-scope="scope">
            {{ scope.row.productNum }}
          </template>
        </el-table-column>
        <el-table-column label="名称">
          <template slot-scope="scope">
            {{ scope.row.productName }}
          </template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template slot-scope="scope">
            {{ scope.row.size }}
          </template>
        </el-table-column>
        <el-table-column label="供应商">
          <template slot-scope="scope">
            {{ scope.row.supplierName }}
          </template>
        </el-table-column>
        <el-table-column label="合格数量">
          <template slot-scope="scope">
            {{ parseInt(scope.row.qualifiedCount) }}
          </template>
        </el-table-column>
        <el-table-column label="不合格数量">
          <template slot-scope="scope">
            {{ parseInt(scope.row.unqualifiedCount) }}
          </template>
        </el-table-column>
        <el-table-column label="已检数量">
          <template slot-scope="scope">
            {{ parseInt(scope.row.inspectedCount) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="base-table-operation">
              <el-link
                size="mini"
                type="primary"
                @click="deleteInspectResult(scope.$index, scope.row)"
                >删除</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 备注 -->
      <el-divider
        class="el-divider-specail el-divider-top"
        content-position="left"
        >检验备注：</el-divider
      >
      <el-input
        v-model="formData.remark"
        type="textarea"
        :rows="3"
        placeholder="请输入检验备注"
        maxlength="1000"
        show-word-limit
      >
      </el-input>
      <!-- 检查验证情况及结果 -->
      <el-divider
        class="el-divider-specail el-divider-top"
        content-position="left"
      >
        <span class="title">检查验证情况及结果：</span>
        <div class="button-area">
          <el-select
            v-model="selectedTestResultValue"
            style="width: 55%; float: left"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in testResultLibrary"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-button type="primary" @click="confirmTestResult()"
            >确认</el-button
          >
        </div>
      </el-divider>
      <el-input
        v-model="testResultContent"
        type="textarea"
        :rows="4"
        placeholder="请输入检查验证情况及结果"
      >
      </el-input>

      <!-- 录入检验结果 Dialog -->
      <InspectResultDialog
        v-if="dialogInspectResultVisible"
        ref="InspectResultDialog"
        :dialog-inspect-result-visible.sync="dialogInspectResultVisible"
        :row-data="rowData"
        @confirmInspectResult="confirmInspectResult"
      >
      </InspectResultDialog>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="cancel">返 回</el-button>
        <el-button type="primary" @click="onSubmit('formData')"
          >检验完成</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserListNoPage } from "../../../../api/Material/Common.js";
import { getInfo } from "../../../../api/Material/MaterialOrderIn.js";
import { create, getTestResultLibrary } from "../../../../api/Material/MaterialInspectionForm.js";
import InspectResultDialog from "./RKInputInspectResultDialog.vue";
export default {
  name: "RKOrderInspect",
  components: { InspectResultDialog },
  props: {
    dialogInspectVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      loading: false,
      innerDialogFormVisible: false,
      dialogInspectResultVisible: false,
      formLabelWidth: "100px",
      sysUserOptions: [],
      testResultLibrary: [],
      rowData: {
        id: 0,
        orderId: 0,
        productId: 0,
        productNum: "",
        productName: "",
        typeName: "",
        size: "",
        packingUnit: "",
        pendingCount: 0,
        qualifiedCount: 0,
        unqualifiedCount: 0,
        inspectedCount: 0,
        supplierId: null,
        supplierName: null
      },
      inspectionChecklist: [],
      initData: {
        id: 0,
        orderId: 0,
        orderNum: "",
        formTypeCode: 0,
        formTypeName: "",
        orderTypeCode: 0,
        orderTypeName: "",
        storageName: "",
        remark: "",
        inspectorId: null,
        inspectorName: null,
        inspectionDate: null,
        inspectionResult: null,
        products: [],
        inspectionDetails: [],
      },
      formData: {
        id: 0,
        orderId: 0,
        orderNum: "",
        formTypeCode: 0,
        formTypeName: "",
        orderTypeCode: 0,
        orderTypeName: "",
        storageName: "",
        remark: "",
        inspectorId: null,
        inspectorName: null,
        inspectionDate: null,
        inspectionResult: null,
        products: [],
        inspectionDetails: [],
      },
      formDataRules: {
        inspectionDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        inspectorId: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        inspectionResult: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        orderNum: "",
        inspectorId: "",
        inspectionDate: "",
        inspectionResult: "",
      },
      errorMsg: {
        orderNum: "",
        inspectorId: "",
        inspectionDate: "",
        inspectionResult: "",
      },
      selectedTestResultValue: null,
      testResultContent: null,
    };
  },
  watch: {
  },
  created() {
    this.innerDialogFormVisible = this.dialogInspectVisible;
    this.init();
  },
  methods: {
    async init() {
      if (this.editId) {
        await this.getDetail();
      }
      this.getOptions();
    },
    getDetail() {
      getInfo({ id: this.editId }).then((res) => {
        this.formData = res.data
        if (res.data && this.formData.products?.length > 0) {
          const productData = res.data.products.map(item => {
            item.pendingCount = item.productCount - item.actualCount;
            return item;
          });
          this.formData.products = productData;
          this.formData.orderId = this.formData.id;
          this.formData.remark = '';
          this.formData.formTypeCode = 100;
          this.formData.formTypeName = '接受检查';
        }
      });
    },
    getOptions() {
      // 检验员
      this.sysUserOptions = [];
      getUserListNoPage({ userStatus: 1 }).then((res) => {
        this.sysUserOptions = res.data;
      }).catch((res) => { });
      // 检查验证情况及结果列表
      this.testResultLibrary = [];
      getTestResultLibrary().then((res) => {
        if (res.data.dataList?.length > 0) {
          this.testResultLibrary = res.data.dataList.map(item => {
            return {
              id: item.resultType,
              label: item.resultType,
              value: item.resultContent
            }
          });
        }
      }).catch((res) => { });
    },
    confirmTestResult() {
      this.testResultContent = this.selectedTestResultValue;
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogInspectVisible", false);
      this.$refs["formData"].resetFields();
      this.$emit("update:editId", "");
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("inspectorId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("inspectionDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("inspectionResult", this.errorMsg, res.msg);
      }
    },
    // 录入检验结果对话框
    openInspectResultDialog(val) {
      this.rowData = {
        id: val.id,
        orderId: val.orderId,
        productId: val.productId,
        productNum: val.number,
        productName: val.name,
        size: val.size,
        typeName: val.typeName,
        packingUnit: val.packingUnit,
        pendingCount: val.pendingCount,
        qualifiedCount: 0,
        unqualifiedCount: 0,
        inspectedCount: 0,
        supplierId: null,
        supplierName: null
      };
      this.dialogInspectResultVisible = true;
    },
    // 确定录入检查结果(回调)
    confirmInspectResult(data) {
      if (data) {
        this.formData.products.map(proItem => {
          if (proItem.id === data.id) {
            proItem.actualCount = parseInt(proItem.actualCount) + parseInt(data.inspectedCount);
            proItem.pendingCount = parseInt(proItem.productCount) - parseInt(proItem.actualCount);
          }
        });

        let isAdd = true;
        this.inspectionChecklist.map(item => {
          if (item.groupkey === data.groupkey) {
            item.qualifiedCount = parseInt(item.qualifiedCount) + parseInt(data.qualifiedCount);
            item.unqualifiedCount = parseInt(item.unqualifiedCount) + parseInt(data.unqualifiedCount);
            item.inspectedCount = parseInt(item.inspectedCount) + parseInt(data.inspectedCount);
            isAdd = false;
          }
        });
        if (isAdd) {
          this.inspectionChecklist.push(data);
        }
      }
    },
    deleteInspectResult(index, val) {
      this.Helper.deleteConfirm(() => {
        const data = this.inspectionChecklist[index];
        this.formData.products.map(proItem => {
          if (proItem.id === data.id) {
            proItem.actualCount = parseInt(proItem.actualCount) - parseInt(data.inspectedCount);
            proItem.pendingCount = parseInt(proItem.productCount) - parseInt(proItem.actualCount);
          }
        });
        this.inspectionChecklist.splice(index, 1);
      });
    },
    // 检验完成
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.inspectionChecklist?.length <= 0) {
            this.$message.error("请录入检验结果");
            return false
          }
          const unfinished = this.formData.products.find(item => parseInt(item.productCount) !== parseInt(item.actualCount));
          if (unfinished) {
            this.$message.error("待检物料未全部检验完成");
            return false
          }
          this.formData.inspectionResult = this.testResultContent;
          if (this.formData.inspectionResult?.length <= 0) {
            this.$message.error("请填写检查验证情况及结果");
            return false
          }
          var flag = false;
          this.formData.products.map(item => {
            if (item.pendingCount > 0) {
              flag = true;
            }
          })
          if (flag) {
            this.$message.error("待检物料的待检数量必须均为已完成，才可进行检验完成操作");
            return false
          }
          // 获取选中人员
          const val = this.formData.inspectorId;
          var userItem = this.sysUserOptions.find(function(i) { return i.id === val });
          this.formData.inspectorName = userItem.name;

          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          const { ...formData } = this.formData;
          if (this.formData.id) {
            create({
              ...formData, Details: this.inspectionChecklist
            }).then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            }).catch(() => {
              this.loading = false;
            });
          } else {
            this.loading = false;
            this.$message.error("参数错误");
            return false
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss">
.order-inspect {
  margin-top: 10px;
  width: 100%;

  .el-dialog__footer .el-button {
    width: 90px;
  }

  .el-table .cell {
    overflow: visible;
  }

  .el-form {
    border: 1px solid #e6ebf5;

    .el-row {
      border-bottom: 1px solid #e6ebf5;

      &:last-child {
        border-bottom: none;
      }

      .el-col {
        &:nth-child(2n + 1) {
          .el-form-item {
            .el-form-item__label {
              border-left: none;
            }
          }
        }

        .el-form-item {
          margin: 0;
          height: 40px;
          line-height: 40px;

          .el-form-item__label {
            height: 100%;
            line-height: 40px;
            background: #f1f8ff;
            border-left: 1px solid #e6ebf5;
            border-right: 1px solid #e6ebf5;
            text-align: center;
            color: #909399;
            font-weight: bold;
          }

          .el-form-item__content {
            text-align: left;
            height: 100%;
            line-height: 40px;
            margin-left: 20px;
          }
        }
      }
    }
  }

  .title {
    display: inline-block;
    vertical-align: middle;
  }

  .el-divider-specail {
    background: transparent;

    .el-divider__text {
      font-weight: bold;
      font-size: 15px;
      left: -20px;
    }

    &.el-divider-top {
      margin-top: 30px;
    }
  }

  .button-area {
    display: inline-block;
    vertical-align: middle;
    margin-left: 10px;
  }
}
</style>
